const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const isProduction = process.env.NODE_ENV === 'production';

const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;

module.exports = {
    mode: 'production',
    context: path.resolve(__dirname, 'src'),
    devtool: isProduction ? false : 'inline-source-map',
    entry: {
        polyfills: ['./content_scripts/js/setup'],
        playback: ['./content_scripts/js/commands-api'],
        service_worker: './background/service_worker',
        record: ['./content_scripts/js/record'],
        escape: ['./content_scripts/js/escape'],
        popup: './popup/popup',
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: '[name].js',
        publicPath: './',
        libraryTarget: 'umd',
    },
    resolve: {
        extensions: ['.js', '.jsx', '.json'],
        alias: {
            '@': path.resolve('src'),
        },
        fallback: {
            stream: false,
            buffer: false,
        },
    },
    module: {
        rules: [
            {
                oneOf: [
                    {
                        test: /\.(js|jsx)$/,
                        include: [path.resolve(__dirname, 'src')],
                        use: {
                            loader: 'babel-loader',
                            options: {
                                plugins: [],
                                presets: ['@babel/preset-env', ['@babel/preset-react', { runtime: 'automatic' }]],
                                sourceType: 'unambiguous',
                            },
                        },
                    },
                    {
                        test: cssRegex,
                        exclude: cssModuleRegex,
                        use: [
                            {
                                loader: MiniCssExtractPlugin.loader,
                                options: {},
                            },
                            {
                                loader: 'css-loader',
                                options: {
                                    importLoaders: 1,
                                    sourceMap: isProduction,
                                    modules: {
                                        mode: 'icss',
                                    },
                                },
                            },
                            {
                                loader: 'postcss-loader',
                                options: {
                                    postcssOptions: {
                                        plugins: [
                                            'tailwindcss',
                                            'postcss-flexbugs-fixes',
                                            [
                                                'postcss-preset-env',
                                                {
                                                    autoprefixer: {
                                                        flexbox: 'no-2009',
                                                    },
                                                    stage: 3,
                                                },
                                            ],
                                            'postcss-normalize',
                                        ],
                                    },
                                    sourceMap: isProduction,
                                },
                            },
                        ],
                        sideEffects: true,
                    },
                    {
                        test: cssModuleRegex,
                        use: [
                            {
                                loader: MiniCssExtractPlugin.loader,
                                options: {},
                            },
                            {
                                loader: 'css-loader',
                                options: {
                                    importLoaders: 1,
                                    sourceMap: isProduction,
                                    modules: {
                                        mode: 'local',
                                        localIdentName: '[local]_[hash:base64:6]',
                                    },
                                },
                            },
                            {
                                loader: 'postcss-loader',
                                options: {
                                    postcssOptions: {
                                        plugins: [
                                            'tailwindcss',
                                            'postcss-flexbugs-fixes',
                                            [
                                                'postcss-preset-env',
                                                {
                                                    autoprefixer: {
                                                        flexbox: 'no-2009',
                                                    },
                                                    stage: 3,
                                                },
                                            ],
                                            'postcss-normalize',
                                        ],
                                    },
                                    sourceMap: isProduction,
                                },
                            },
                        ],
                    },
                    {
                        test: sassRegex,
                        exclude: sassModuleRegex,
                        use: [
                            {
                                loader: require.resolve('sass-loader'),
                                options: {
                                    sourceMap: isProduction,
                                },
                            },
                        ].filter(Boolean),
                        sideEffects: true,
                    },
                    {
                        test: sassModuleRegex,
                        use: [
                            {
                                loader: MiniCssExtractPlugin.loader,
                                options: {},
                            },
                            {
                                loader: 'css-loader',
                                options: {
                                    importLoaders: 3,
                                    sourceMap: isProduction,
                                    modules: {
                                        mode: 'local',
                                        localIdentName: '[local]_[hash:base64:6]',
                                    },
                                },
                            },
                            {
                                loader: 'postcss-loader',
                                options: {
                                    postcssOptions: {
                                        plugins: [
                                            'tailwindcss',
                                            'postcss-flexbugs-fixes',
                                            [
                                                'postcss-preset-env',
                                                {
                                                    autoprefixer: {
                                                        flexbox: 'no-2009',
                                                    },
                                                    stage: 3,
                                                },
                                            ],
                                            'postcss-normalize',
                                        ],
                                    },
                                    sourceMap: isProduction,
                                },
                            },
                            {
                                loader: require.resolve('sass-loader'),
                                options: {
                                    sourceMap: isProduction,
                                },
                            },
                        ].filter(Boolean),
                    },
                    {
                        test: lessRegex,
                        exclude: lessModuleRegex,
                        use: [
                            {
                                loader: MiniCssExtractPlugin.loader,
                                options: {},
                            },
                            {
                                loader: 'css-loader',
                                options: {
                                    importLoaders: 3,
                                    sourceMap: isProduction,
                                    modules: {
                                        mode: 'icss',
                                    },
                                },
                            },
                            {
                                loader: 'postcss-loader',
                                options: {
                                    postcssOptions: {
                                        plugins: [
                                            'tailwindcss',
                                            'postcss-flexbugs-fixes',
                                            [
                                                'postcss-preset-env',
                                                {
                                                    autoprefixer: {
                                                        flexbox: 'no-2009',
                                                    },
                                                    stage: 3,
                                                },
                                            ],
                                            'postcss-normalize',
                                        ],
                                    },
                                    sourceMap: isProduction,
                                },
                            },
                            {
                                loader: require.resolve('less-loader'),
                                options: {
                                    lessOptions: {
                                        strictMath: true,
                                        javascriptEnabled: true,
                                        modifyVars: {
                                            // colorPrimary: 'red',
                                        },
                                    },
                                    sourceMap: isProduction,
                                },
                            },
                        ].filter(Boolean),
                        sideEffects: true,
                    },
                    {
                        test: lessModuleRegex,
                        use: [
                            {
                                loader: MiniCssExtractPlugin.loader,
                                options: {},
                            },
                            {
                                loader: 'css-loader',
                                options: {
                                    importLoaders: 3,
                                    sourceMap: isProduction,
                                    modules: {
                                        mode: 'local',
                                        localIdentName: '[local]_[hash:base64:6]',
                                    },
                                },
                            },
                            {
                                loader: 'postcss-loader',
                                options: {
                                    postcssOptions: {
                                        plugins: [
                                            'tailwindcss',
                                            'postcss-flexbugs-fixes',
                                            [
                                                'postcss-preset-env',
                                                {
                                                    autoprefixer: {
                                                        flexbox: 'no-2009',
                                                    },
                                                    stage: 3,
                                                },
                                            ],
                                            'postcss-normalize',
                                        ],
                                    },
                                    sourceMap: isProduction,
                                },
                            },
                            {
                                loader: 'less-loader',
                                options: {
                                    lessOptions: {
                                        javascriptEnabled: true,
                                        modifyVars: {
                                            // colorPrimary: 'red',
                                        },
                                    },
                                    sourceMap: isProduction,
                                },
                            },
                        ].filter(Boolean),
                    },
                    {
                        test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
                        loader: 'url-loader',
                        options: {
                            limit: 50 * 1024,
                            name: 'static/images/[name]-[hash:5].[ext]',
                            esModule: false,
                        },
                        type: 'javascript/auto',
                    },
                    {
                        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                        exclude: [path.resolve(__dirname, '../src/assets')],
                        use: [
                            {
                                loader: 'url-loader',
                                options: {
                                    name: '[name]-[hash].[ext]',
                                    outputPath: 'images/',
                                    limit: 204800,
                                },
                            },
                        ],
                    },
                    {
                        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                        include: [path.resolve(__dirname, '../src/assets')],
                        use: [
                            {
                                loader: 'babel-loader',
                                options: {
                                    presets: ['@babel/preset-react', '@babel/preset-env'],
                                },
                            },
                            {
                                loader: '@svgr/webpack',
                                options: {
                                    babel: false,
                                    icon: true,
                                },
                            },
                        ],
                    },
                    {
                        exclude: [/^$/, /\.(js|mjs|jsx)$/, /\.html$/, /\.json$/],
                        type: 'asset/resource',
                    },
                ],
            },
        ],
    },
    plugins: [
        new CleanWebpackPlugin({
            cleanOnceBeforeBuildPatterns: [path.resolve(__dirname, './build/*')],
        }),
        new CopyWebpackPlugin({
            patterns: [
                path.resolve(__dirname, './public/manifest.json'),
                path.resolve(__dirname, './src/indicator/indicator.html'),
                path.resolve(__dirname, './src/indicator/indicator.js'),
                path.resolve(__dirname, './public/bootstrap.html'),
                path.resolve(__dirname, './public/global.js'),
                path.resolve(__dirname, './public/prompt.js'),
                {
                    from: path.resolve(__dirname, './public/icons'),
                    to: path.resolve(__dirname, './build/icons'),
                },
            ],
        }),
        new HtmlWebpackPlugin({
            filename: 'popup.html',
            inject: true,
            template: path.resolve(__dirname, 'src/popup/popup.html'),
            chunks: ['popup'],
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true,
            },
        }),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify(process.env.NODE_ENV),
                USE_WEBDRIVER: JSON.stringify(process.env.USE_WEBDRIVER),
            },
        }),
        new MiniCssExtractPlugin({
            filename: 'css/[name].css',
        }),
    ],
};
